package io.github.wppli.trigger.http;

import cc.jq1024.middleware.token.service.ITokenService;
import io.github.wppli.domain.posts.model.entity.CollectPostsEntity;
import io.github.wppli.domain.posts.model.entity.PostEntity;
import io.github.wppli.domain.posts.model.entity.PublishPostsEntity;
import io.github.wppli.domain.posts.model.entity.LikePostsEntity;
import io.github.wppli.domain.posts.model.http.PublishPostsRequest;
import io.github.wppli.domain.posts.model.valobj.PostsStatus;
import io.github.wppli.domain.posts.service.IPostsService;
import io.github.wppli.types.exception.AppException;
import io.github.wppli.types.model.Response;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 内容帖子控制器
 * @author li--jiaqiang 2025−03−11
 */
@Slf4j
@RestController
@RequestMapping("/posts")
@AllArgsConstructor
@CrossOrigin(value = {"${app.config.cross-origin:http://116.198.239.101:3000/}", "http://localhost:3000/"})
public class PostsController {

    private final ITokenService tokenService;

    private final IPostsService postsService;

    /**
     * 发布帖子
     */
    @PostMapping("/publish")
    public Response<String> publishPosts(@RequestBody PublishPostsRequest publishPostsRequest,
                                         @RequestHeader("Authorization") String authorization)  {
        try {
            // 1. 参数校验
            publishPostsRequest.validate();
            // 2. 获取用户信息
            String token = authorization.replace("Bearer ", "");
            String userId = tokenService.decode(token).getSubject();
            PublishPostsEntity publishPostsEntity = PublishPostsEntity.builder()
                        .authorId(Long.parseLong(userId))
                        .images(publishPostsRequest.getImages())
                        .title(publishPostsRequest.getTitle())
                        .content(publishPostsRequest.getContent())
                        .isPublic(publishPostsRequest.getIsPublic())
                        .postsStatus(PostsStatus.NORMAL)
                        .build();
            postsService.publishPosts(publishPostsEntity);

            return Response.ok("发布成功");
        } catch (AppException exception) {
            log.error("AppException: ",exception);
            return Response.<String>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ",exception);
            return Response.systemError();
        }
    }

    /**
     * 查询帖子列表
     */
    @GetMapping("/list/{authorId}")
    public Response<List<PostEntity>> listPosts(@PathVariable("authorId") Long authorId) {
        try {
            List<PostEntity> postEntities = postsService.listPosts(authorId);
            return Response.ok(postEntities);
        } catch (AppException exception) {
            log.error("AppException: ",exception);
            return Response.<List<PostEntity>>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ",exception);
            return Response.systemError();
        }
    }

    /**
     * 获取单个帖子
     */
    @GetMapping("/{postId}")
    public Response<PostEntity> getPosts(@PathVariable("postId") Long postId) {
        try {
            PostEntity postEntity = postsService.getPosts(postId);
            return Response.ok(postEntity);
        } catch (AppException exception) {
            log.error("AppException: ",exception);
            return Response.<PostEntity>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ",exception);
            return Response.systemError();
        }
    }

    /**
     * 删除帖子
     */
    @PostMapping("/delete/{postId}")
    public Response<String> deletePosts(@PathVariable("postId") Long postId,
                                        @RequestHeader("Authorization") String authorization) {
        try {
            String token = authorization.replace("Bearer ", "");
            String userId = tokenService.decode(token).getSubject();
            postsService.deletePosts(postId, Long.parseLong(userId));
            return Response.ok("删除成功");
        } catch (AppException exception) {
            log.error("AppException: ",exception);
            return Response.<String>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ",exception);
            return Response.systemError();
        }
    }

    /**
     * 用户点赞帖子
     */
    @PostMapping("/like/{postId}")
    public Response<String> likePosts(@PathVariable("postId") Long postId,
                                      @RequestHeader("Authorization") String authorization)  {
        try {
            String token = authorization.replace("Bearer ", "");
            String userId = tokenService.decode(token).getSubject();
            LikePostsEntity likePostsEntity = LikePostsEntity.builder()
                    .postsId(postId)
                    .adjustCount(1)
                    .userId(Long.parseLong(userId)).build();
            postsService.likePosts(likePostsEntity);
            return Response.ok();
        } catch (AppException exception) {
            log.error("AppException: ", exception);
            return Response.<String>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ", exception);
            return Response.systemError();
        }
    }

    /**
     * 用户取消点赞帖子
     */
    @PostMapping("/unlike/{postId}")
    public Response<String> unLikePosts(@PathVariable("postId") Long postId,
                                      @RequestHeader("Authorization") String authorization)  {
        try {
            String token = authorization.replace("Bearer ", "");
            String userId = tokenService.decode(token).getSubject();
            LikePostsEntity likePostsEntity = LikePostsEntity.builder()
                    .postsId(postId)
                    .adjustCount(-1)
                    .userId(Long.parseLong(userId)).build();
            postsService.unLikePosts(likePostsEntity);
            return Response.ok();
        } catch (AppException exception) {
            log.error("AppException: ", exception);
            return Response.<String>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ", exception);
            return Response.systemError();
        }
    }


    /**
     * 用户收藏帖子
     */
    @PostMapping("/collect/{postId}")
    public Response<String> collectPosts(@PathVariable("postId") Long postId,
                                         @RequestHeader("Authorization") String authorization)  {
        try {
            String token = authorization.replace("Bearer ", "");
            String userId = tokenService.decode(token).getSubject();
            CollectPostsEntity collectPostsEntity = CollectPostsEntity.builder()
                    .postsId(postId)
                    .userId(Long.parseLong(userId))
                    .adjustCount(1)
                    .build();
            postsService.collectPosts(collectPostsEntity);
            return Response.ok();
        } catch (AppException exception) {
            log.error("AppException: ", exception);
            return Response.<String>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ", exception);
            return Response.systemError();
        }
    }


    /**
     * 取消收藏帖子
     */
    @PostMapping("/unCollect/{postId}")
    public Response<String> unCollects(@PathVariable("postId") Long postId,
                                         @RequestHeader("Authorization") String authorization)  {
        try {
            String token = authorization.replace("Bearer ", "");
            String userId = tokenService.decode(token).getSubject();
            CollectPostsEntity collectPostsEntity = CollectPostsEntity.builder()
                    .postsId(postId)
                    .userId(Long.parseLong(userId))
                    .adjustCount(-1)
                    .build();
            postsService.unCollectPosts(collectPostsEntity);
            return Response.ok();
        } catch (AppException exception) {
            log.error("AppException: ", exception);
            return Response.<String>builder()
                    .code(exception.getCode())
                    .info(exception.getInfo())
                    .build();
        } catch (Exception exception) {
            log.error("Exception: ", exception);
            return Response.systemError();
        }
    }
}